package com.orm.mybatis.config;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.mysql.cj.jdbc.MysqlXADataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
@MapperScan(basePackages = Master1DataSourceConfig.PACKAGE, sqlSessionTemplateRef = "master1SqlSessionTemplate")
public class Master1DataSourceConfig {
    static final String PACKAGE = "com.orm.mybatis.mapper.master1";
    static final String MAPPER_LOCATION = "classpath:mapper/master1/*.xml";

    @Value("${master1.url}")
    private String url;

    @Value("${master1.username}")
    private String user;

    @Value("${master1.password}")
    private String password;

    @Value("${master1.driverClassName}")
    private String driverClass;

//    @Bean(name = "master1DataSource")     //非分布式事务数据源
//    public DataSource master1DataSource() {
////        DataSource dataSource = DataSourceBuilder.create().driverClassName(driverClass).password(password).url(url).username(user).build();
//         HikariDataSource hikariDataSource = new HikariDataSource();
//         hikariDataSource.setJdbcUrl(url);
//         hikariDataSource.setUsername(user);
//         hikariDataSource.setDriverClassName(driverClass);
//         hikariDataSource.setPassword(password);
//         hikariDataSource.setMinimumIdle(5);
//         hikariDataSource.setMaximumPoolSize(20);
//         hikariDataSource.setAutoCommit(true);
//         hikariDataSource.setPoolName("SpringBootDemoHikariCP");
//         hikariDataSource.setMaxLifetime(60000);
//         hikariDataSource.setConnectionTimeout(30000);
//        return hikariDataSource;
//    }

    @Bean(name = "master1DataSource")    //分布式事务数据源
    public DataSource master1DataSource() throws SQLException {
        MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();
        mysqlXaDataSource.setUrl(url);
        mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
        mysqlXaDataSource.setPassword(password);
        mysqlXaDataSource.setUser(user);
        mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
        // 将本地事务注册到创 Atomikos全局事务
        AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
        xaDataSource.setXaDataSource(mysqlXaDataSource);
        xaDataSource.setUniqueResourceName("master1DataSource");
        xaDataSource.setMinPoolSize(5);
        xaDataSource.setMaxPoolSize(20);
        xaDataSource.setMaxLifetime(60000);
        xaDataSource.setBorrowConnectionTimeout(30);
        xaDataSource.setLoginTimeout(30);
        xaDataSource.setMaintenanceInterval(60);
        xaDataSource.setMaxIdleTime(60);
        return xaDataSource;
    }

// 非分布式事务
//    @Bean(name = "master1TransactionManager")
//    public DataSourceTransactionManager masterTransactionManager(@Qualifier("master1DataSource") DataSource masterDataSource) {
//        return new DataSourceTransactionManager(masterDataSource);
//    }

    @Bean(name = "master1SqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("master1DataSource") DataSource masterDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(masterDataSource);
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        sessionFactory.setConfiguration(configuration);
        sessionFactory.setTypeAliasesPackage("com.orm.mybatis.entity");
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(Master1DataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

    @Bean(name = "master1SqlSessionTemplate")         //添加这个就不用@primary
    public SqlSessionTemplate test2SqlSessionTemplate(@Qualifier("master1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
